package com.yixia.camera.demo.ui.record;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import android.annotation.TargetApi;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.media.MediaMetadataRetriever;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnErrorListener;
import android.media.MediaPlayer.OnInfoListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.os.Build;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout.LayoutParams;

import com.nostra13.universalimageloader.core.ImageLoader;
import com.xindaoapp.happypet.R;
import com.xindaoapp.happypet.application.HappyPetApplication;
import com.xindaoapp.happypet.utils.CommonUtil;
import com.xindaoapp.happypet.utils.IRequest;
import com.yixia.camera.demo.ui.BaseActivity;
import com.yixia.camera.demo.ui.widget.SurfaceVideoView;
import com.yixia.camera.util.DeviceUtils;
import com.yixia.camera.util.StringUtils;

/**
 * 通用单独播放界面
 * 
 * @author tangjun
 * 
 */
public class VideoPlayerActivity extends BaseActivity implements
        SurfaceVideoView.OnPlayStateListener, OnErrorListener, OnPreparedListener, OnClickListener,
        OnCompletionListener, OnInfoListener {

    /** 播放控件 */
    private SurfaceVideoView mVideoView;
    /** 暂停按钮 */
    private View mPlayerStatus;
    private View mLoading;
    private View mUserVideo;
    private View mCancelVideo;
    private ImageView mCoverImage;

    /** 播放路径 */
    private String mPath;
    /** 是否需要回复播放 */
    private boolean mNeedResume;

    private int mCurrentPosition = 0;
    private View[] mStateViews;
    private List<String> mCoverList = new ArrayList<String>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 防止锁屏
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

        mPath = getIntent().getStringExtra("path");
        if (StringUtils.isEmpty(mPath)) {
            finish();
            return;
        }

        setContentView(R.layout.activity_video_player);
        mVideoView = (SurfaceVideoView) findViewById(R.id.videoview);
        mPlayerStatus = findViewById(R.id.play_status);
        mLoading = findViewById(R.id.loading);
        mUserVideo = findViewById(R.id.user_video);
        mCancelVideo = findViewById(R.id.cancel);
        mCoverImage = (ImageView) findViewById(R.id.cover);

        mVideoView.setOnPreparedListener(this);
        mVideoView.setOnPlayStateListener(this);
        mVideoView.setOnErrorListener(this);
        mVideoView.setOnClickListener(this);
        mVideoView.setOnInfoListener(this);
        mVideoView.setOnCompletionListener(this);

        mVideoView.getLayoutParams().height = DeviceUtils.getScreenWidth(this);

        findViewById(R.id.root).setOnClickListener(this);
        mVideoView.setVideoPath(mPath);

        mPlayerStatus.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                mVideoView.start();
                play(true);
            }
        });

        mCancelVideo.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                finish();
            }
        });

        mUserVideo.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // 使用，发送一条广播
                Intent intent = new Intent("record_video_finish");
                intent.putExtra("video_path", mPath);
                intent.putExtra("video_cover_path", mCoverList.get(mCurrentPosition));
                sendBroadcast(intent);
                setResult(RESULT_OK);
                finish();
            }
        });
        final ProgressDialog dialog = new ProgressDialog(this);
        dialog.setMessage("视频处理中...");
        dialog.show();
        parseImageCovers(new IRequest<List<String>>() {

            @Override
            public void request(List<String> t) {
                mCoverList = t;
                dialog.dismiss();
                mUserVideo.setVisibility(View.VISIBLE);
                mCancelVideo.setVisibility(View.VISIBLE);
                play(false);
                initCovers(t);
            }
        });

    }

    /**
     * 改变播放状态
     * 
     * @param start
     */
    private void play(boolean start) {
        if (start) {
            // mVideoView.start();
            mCoverImage.setVisibility(View.GONE);
            mPlayerStatus.setVisibility(View.GONE);
        } else {
            // mVideoView.pause();
            // 显示封面
            ImageLoader.getInstance().displayImage("file://" + mCoverList.get(mCurrentPosition),
                    mCoverImage);
            mCoverImage.setVisibility(View.VISIBLE);
            mPlayerStatus.setVisibility(View.VISIBLE);
        }

    }

    @Override
    public void onResume() {
        super.onResume();
        if (mVideoView != null && mNeedResume) {
            mNeedResume = false;
            if (mVideoView.isRelease()) {
                mVideoView.reOpen();
            } else {
                mVideoView.start();
            }
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        if (mVideoView != null) {
            if (mVideoView.isPlaying()) {
                mNeedResume = true;
                mVideoView.pause();
            }
        }
    }

    @Override
    protected void onDestroy() {
        if (mVideoView != null) {
            mVideoView.release();
            mVideoView = null;
        }
        super.onDestroy();
    }

    @Override
    public void onPrepared(MediaPlayer mp) {
        mVideoView.setVolume(SurfaceVideoView.getSystemVolumn(this));
        // mVideoView.start();
        // new Handler().postDelayed(new Runnable() {
        //
        // @SuppressWarnings("deprecation")
        // @Override
        // public void run() {
        // if (DeviceUtils.hasJellyBean()) {
        // mVideoView.setBackground(null);
        // } else {
        // mVideoView.setBackgroundDrawable(null);
        // }
        // }
        // }, 300);
        mLoading.setVisibility(View.GONE);
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        switch (event.getKeyCode()) {// 跟随系统音量走
            case KeyEvent.KEYCODE_VOLUME_DOWN:
            case KeyEvent.KEYCODE_VOLUME_UP:
                mVideoView.dispatchKeyEvent(this, event);
                break;
        }
        return super.dispatchKeyEvent(event);
    }

    private final boolean isFrist = true;

    @Override
    public void onStateChanged(boolean isPlaying) {
        // if (isFrist) {
        // mVideoView.pause();
        // isFrist = false;
        // }
        // mPlayerStatus.setVisibility(isPlaying ? View.GONE : View.VISIBLE);

        play(isPlaying);
    }

    @Override
    public boolean onError(MediaPlayer mp, int what, int extra) {
        if (!isFinishing()) {
            // 播放失败
        }
        finish();
        return false;
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.root) {
        } else if (v.getId() == R.id.videoview) {
            if (mVideoView.isPlaying()) {
                mVideoView.pause();

            } else {
                mVideoView.start();
            }
        }
    }

    @Override
    public void onCompletion(MediaPlayer mp) {
        if (!isFinishing())
            mVideoView.reOpen();
    }

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    @Override
    public boolean onInfo(MediaPlayer mp, int what, int extra) {
        switch (what) {
            case MediaPlayer.MEDIA_INFO_BAD_INTERLEAVING:
                // 音频和视频数据不正确
                break;
            case MediaPlayer.MEDIA_INFO_BUFFERING_START:
                if (!isFinishing())
                    mVideoView.pause();
                break;
            case MediaPlayer.MEDIA_INFO_BUFFERING_END:
                if (!isFinishing())
                    mVideoView.start();
                break;
            case MediaPlayer.MEDIA_INFO_VIDEO_RENDERING_START:
                if (DeviceUtils.hasJellyBean()) {
                    mVideoView.setBackground(null);
                } else {
                    mVideoView.setBackgroundDrawable(null);
                }
                break;
        }
        return false;
    }

    /**
     * 初始化封面
     */
    private void initCovers(List<String> list) {
        LinearLayout container = (LinearLayout) findViewById(R.id.container);

        DisplayMetrics metric = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metric);

        if (null != list) {
            mStateViews = new View[list.size()];

            for (int i = 0; i < list.size(); i++) {
                final View view = getLayoutInflater().inflate(R.layout.item_image, null);
                final ImageView imageView = (ImageView) view.findViewById(R.id.icon);
                android.view.ViewGroup.LayoutParams params =
                        new LayoutParams(metric.widthPixels / 4, metric.widthPixels / 4);
                ImageLoader.getInstance().displayImage("file://" + list.get(i), imageView);
                mStateViews[i] = view.findViewById(R.id.state);
                final int index = i;
                view.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        setState(index);
                        mVideoView.pause();

                        play(false);
                    }
                });
                container.addView(view, params);
            }
            setState(0);
        }
    }

    private void setState(int position) {
        mCurrentPosition = position;
        for (int i = 0; i < mStateViews.length; i++) {
            if (i == position) {
                mStateViews[i].setVisibility(View.VISIBLE);
            } else {
                mStateViews[i].setVisibility(View.GONE);
            }
        }
    }

    private void parseImageCovers(final IRequest<List<String>> iRequest) {
        new Thread(new Runnable() {

            @Override
            public void run() {
                MediaMetadataRetriever mediaMetadataRetriever = new MediaMetadataRetriever();

                mediaMetadataRetriever.setDataSource(mPath);
                long duration =
                        Long.parseLong(mediaMetadataRetriever
                                .extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION));
                final List<String> files = new ArrayList<String>();

                CommonUtil.mkFiledir("/sdcard/happypet/covers/");
                String parentFilePath = "/sdcard/happypet/covers/" + System.currentTimeMillis();
                CommonUtil.mkFiledir(parentFilePath);
                for (int i = 0; i < duration / 1000; i++) {
                    String filePath =
                            parentFilePath + File.separator + System.currentTimeMillis() + ".jpg";
                    if (bitmapToFile(mediaMetadataRetriever.getFrameAtTime(i * 1000000,
                            MediaMetadataRetriever.OPTION_CLOSEST_SYNC), filePath)) {
                        files.add(filePath);
                    }
                }
                HappyPetApplication.mHandler.post(new Runnable() {

                    @Override
                    public void run() {
                        iRequest.request(files);
                    }
                });
            }
        }).start();
    }

    private boolean bitmapToFile(Bitmap bitmap, String filePath) {
        FileOutputStream fos = null;
        try {
            // create a file to write bitmap data
            File f = new File(filePath);
            f.createNewFile();

            // Convert bitmap to byte array
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            bitmap.compress(CompressFormat.PNG, 0 /* ignored for PNG */, bos);
            byte[] bitmapdata = bos.toByteArray();

            // write the bytes in file
            fos = new FileOutputStream(f);
            fos.write(bitmapdata);
            return true;
        } catch (Exception e) {
        } finally {
            if (null != fos) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return false;
    }
}
